<?php
namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Log;
class PayOrdercatrController extends Controller
{

    /**
     * 创建订单接口
     */                            
    public function createDLBPay($orderSn, $bankType = 'WX', $amount, $openid,$merchantInfo)
    {
        // body体
        $sign_data = array(
            'agentNum' => '10001016014493267623026',//'10001116024791588399078', // 代理商编号
            'amount' => $amount,                          // 金额--请求传递
            'authId' => $openid,//'ojiuXuA3uRjfHd6LtbSfs51Q2UjQ',
            //'callbackUrl' => 'http://hrcc8.com/api/callbackOrdercart', 
            'callbackUrl' => 'http://hrcc8.com/api/callbackOrdercatr',                // 回调服务器链接--请求传递
            'customerNum' => $merchantInfo->customerNum,//'10001116024791588399078',//'10001116024791588399078',           // 哆啦宝商户号--请求传递
            'requestNum' => $orderSn,                 // 订单号--请求传递  注：必须为18-32位纯数字
            'shopNum' =>  $merchantInfo->shopNum,//'10001216024797309358302',//'10001214504254906302068',                   // 哆啦宝店铺号--请求传递
            'source' => 'API',
            'bankType' => $bankType,
        );
        $params['secretkey'] = $merchantInfo->shopSecret;//'23bfadd7aea540f896814e20641f118790a9ded3';
        $params['accesskey'] = $merchantInfo->shopAccess;
        $params['timestamp'] = $this->getMillisecond();
        $params['path'] = '/v3/order/pay/create';
        $params['body'] = json_encode($sign_data);
        $infoArr = $this->creatTokenPost($params);
        return $infoArr;
    }

    /**
     * 退款接口
     */
    public function refundDLBPay($ordersn,$refundOrder,$merchantInfo,$refundPartAmount='')
    {
        $sign_data = array(
            'agentNum' => '10001016014493267623026',//'10001116024791588399078', // 代理商编号
            'customerNum' => $merchantInfo->customerNum,//'10001116024791588399078',//'10001116024791588399078',           // 哆啦宝商户号--请求传递
            'requestNum' => $ordersn,                 // 订单号--请求传递  注：必须为18-32位纯数字
            'shopNum' => $merchantInfo->shopNum,//'10001214504254906302068',                   // 哆啦宝店铺号--请求传递
            'source' => 'API',
            'refundRequestNum'=> $refundOrder,
            'refundPartAmount' => $refundPartAmount,
        );
        $path = $refundPartAmount == '' ? '/v3/order/refund' : '/v3/order/refund/part';
        //$path = '/v3/order/refund';
        $params['secretkey'] = $merchantInfo->shopSecret;//'23bfadd7aea540f896814e20641f118790a9ded3';
        $params['accesskey'] = $merchantInfo->shopAccess;
        $params['timestamp'] = $this->getMillisecond();
        $params['path'] = $path;
        $params['body'] = json_encode($sign_data);
        $infoArr = $this->creatTokenPost($params);
        return  $infoArr;
    }
    /**
     * 创建哆啦宝微信支付
     */
    protected function request_createpay($data)
    {
        if ($data['dlb_customer_num']) {
            $pay_data['accesskey'] = '62694e2e777844e39e2ddb75869ce8f9c0f999b8';//'e84fab7878194925a28f5ee8e926e77f913cc646';//$PayConfig['dlb_access_key'];
            $pay_data['secretkey'] = 'dba2df87597440fd8c0444dec3b65262dcbf3f38';//'d9bb7fc0493647a48e937ded073e342280dd45ac';//$PayConfig['dlb_secret_key'];
            $pay_data['timestamp'] = $this->getMillisecond();
            $pay_data['path'] = '/v1/agent/order/payurl/create';//$PayConfig['dlb_path_createorder']; //'/v1/agent/order/payurl/create';
            $sign_data = array(
                'agentNum' => 10001014472963095391100,//$PayConfig['dlb_agent_num'],            // 代理商编号
                'amount' => 0.01,                          // 金额--请求传递
                'callbackUrl' => $data['callback_url'],               // 回调服务器链接--请求传递
                'customerNum' => $data['dlb_customer_num'],           // 哆啦宝商户号--请求传递
                'requestNum' => $data['request_num'],                 // 订单号--请求传递  注：必须为18-32位纯数字
                'shopNum' => $data['dlb_shop_num'],                   // 哆啦宝店铺号--请求传递
                'source' => 'API',
            );
            //dd($pay_data,12341);
            $pay_data['body'] = json_encode($sign_data);
            $infoArr = $this->creatTokenPost($pay_data);
            switch ($infoArr['result']) {
                case 'success'://成功
                    $payurl = $infoArr['data']['url'];
                    return array('code' => 200, 'msg' => '订单支付创建成功', 'url' => array('payurl' => $payurl));
                    break;
                case 'fail'://失败
                    return array('code' => 502, 'msg' => '订单支付创建失败');
                    break;
                case 'error'://异常
                    return array('code' => 501, 'msg' => '服务器繁忙，支付调用失败');
                    break;
                default:

                    break;
            }
        } else {
            return array('code' => 502, 'msg' => '订单支付创建失败');
        }
    }

    /**
     * 申请哆啦宝微信退款
     */
    protected function request_refundpay($data)
    {
        echo "**" . $data['dlb_customer_num'] . "**" . $data['dlb_shop_num'] . "**" . $data['request_num'] . "**";
        $PayConfig = $this->config('dlbpay');
        if (is_array($PayConfig)) {
            $pay_data['accesskey'] = $PayConfig['dlb_access_key'];
            $pay_data['secretkey'] = $PayConfig['dlb_secret_key'];
            $pay_data['timestamp'] = $this->getMillisecond();
            $pay_data['path'] = $PayConfig['dlb_path_refund'];      //'/v1/agent/order/payurl/create';
            $sign_data = array(
                'agentNum' => $PayConfig['dlb_agent_num'],            // 代理商编号
                'customerNum' => $data['dlb_customer_num'],           // 哆啦宝商户号--请求传递
                'requestNum' => $data['request_num'],                 // 订单号--请求传递  注：必须为18-32位纯数字
                'shopNum' => $data['dlb_shop_num'],                   // 哆啦宝店铺号--请求传递
            );
            $pay_data['body'] = json_encode($sign_data);
            $infoArr = $this->creatTokenPost($pay_data);
            switch ($infoArr['result']) {
                case 'success'://成功
                    $payurl = $infoArr['data']['url'];
                    return array('code' => 200, 'msg' => '订单退款成功', 'url' => array('payurl' => $payurl));
                    break;
                case 'fail'://失败
                    return array('code' => 502, 'msg' => '订单退款失败');
                    break;
                case 'error'://异常
                    return array('code' => 501, 'msg' => '服务器繁忙，退款失败，请稍后再试试');
                    break;
                default:
                    break;
            }
        } else {
            return array('code' => 502, 'msg' => '订单退款失败');
        }
    }

    //生成token并提交
    protected function creatTokenPost($data)
    {
        $str = "secretKey={$data['secretkey']}&timestamp={$data['timestamp']}&path={$data['path']}&body={$data['body']}";
        $token = strtoupper(sha1($str));
        $url = 'https://openapi.duolabao.com' . $data['path'];

        $post_data = $data['body'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'accesskey: ' . $data['accesskey'],
                'timestamp: ' . $data['timestamp'],
                'token: ' . $token)
        );
        $info = curl_exec($ch);
        $infoArr = json_decode($info, true);

        curl_close($ch);
        return $infoArr;
    }

    /**13位时间戳**/
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return $t2 . ceil(($t1 * 1000));
    }

    // 支付状态
    public function payStatus($orderSn,$merchantInfo){
        $path = '/v3/order/query';
        // body体
        $sign_data = array(
            'agentNum' => '10001016014493267623026',//'10001116024791588399078', // 代理商编号
            'customerNum' => $merchantInfo->customerNum,//'10001116024791588399078',//'10001116024791588399078',           // 哆啦宝商户号--请求传递
            'requestNum' => $orderSn,                 // 订单号--请求传递  注：必须为18-32位纯数字
            'shopNum' => $merchantInfo->shopNum,//'10001216024797309358302',//'10001214504254906302068',                   // 哆啦宝店铺号--请求传递
            'source' => 'API',
        );
    
        $params['secretkey'] = $merchantInfo->shopSecret;//'23bfadd7aea540f896814e20641f118790a9ded3';
        $params['accesskey'] = $merchantInfo->shopAccess;
        $params['timestamp'] = $this->getMillisecond();
        $params['path'] = $path;
        $params['body'] = json_encode($sign_data);
        $infoArr = $this->creatTokenPost($params);
        return $infoArr;
    }


}

